const { createApp, ref, reactive, onMounted } = Vue;
const app = createApp({
  setup() {
    let value = ref({})
    let shu = ref({})
    let News_Category = ref('')
    let input = ref({
      searchText: '' // 明确字段名称
    })
    let totalMembers = ref("8888")

    let form = reactive({})
    let tableData = ref([])
    const activeName = ref('first')
    // 弹出层
    let dialogVisible = ref(false)
    let diaModify = ref(false)
    let News_modfiy = ref('')



    const handleAdd = () => {
      console.log('添加111');
      dialogVisible.value = true



    }

    // 弹出层编辑
    const handleModify = (data) => {
      console.log('修改', data);
      diaModify.value = true
      News_modfiy.value = data.News_Category
      // console.log(data.News_Category);
      shu = data







    }

    const Cancel = () => {
      dialogVisible.value = false
    }

    const Cancels = () => {
      diaModify.value = false
    }

    const disabledModify = () => {
      console.log('确认修改', shu);
      shu.News_Category = News_modfiy
      console.log(shu);
      let biao = new Object()
      biao.Modify = { news_category: [shu] }
      console.log('biao', biao);




      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/generalSave",
        method: "post",
        data: {
          Data: JSON.stringify(biao),
        },
        success: (res) => {
          console.log(res);
          queryTree()
        },
      });





    }

    // 弹出层删除
    const handleDel = (data) => {
      console.log(data);
      data.Row_Status = '88'
      console.log(data);
      let a = new Array()
      a.push(data)
      let b = new Object()
      b.Modify = { news_category: a }
      console.log('b', b);
      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/generalSave",
        method: "post",
        data: {
          Data: JSON.stringify(b),
        },
        success: (res) => {
          console.log(res);
          queryTree()
        },
      });
    }
    // 添加
    const queren = () => {
      console.log('测试111', News_Category.value);
      let lsNews_Category = News_Category.value
      console.log('lsNews_Category', lsNews_Category);
      let cun = { Add: { news_category: [{ News_Category: lsNews_Category }] } }
      console.log('a', cun);
      dialogVisible.value = false

      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/generalSave",
        method: "post",
        data: {
          Data: JSON.stringify(cun),
          Condition: '', // 查询条件
        },
        success: (res) => {
          console.log(res);
          queryTree()
        },
      });
    }

    // 点击查询
    const check = () => {
      // 获取输入框中的搜索文本
      const searchText = input.value.searchText;
      // 获取当前选中的分类编号（假设 treexw 是从其他地方获取的分类编号）
      const categorySerialNumber = value._value;
      console.log('点击了查询，搜索文本:', searchText, categorySerialNumber);
      // return;
      // 构造查询条件
      let condition = '';
      if (searchText && categorySerialNumber) {
        // 如果同时有标题和分类编号，则组合查询条件
        condition = `News_Title LIKE '%${searchText}%' AND News_Category_SerialNumber='${categorySerialNumber}'`;
      } else if (searchText) {
        // 如果只有标题，则只按标题查询
        condition = `News_Title LIKE '%${searchText}%'`;
      } else if (categorySerialNumber) {
        // 如果只有分类编号，则只按分类编号查询
        condition = `News_Category_SerialNumber='${categorySerialNumber}'`;
      }

      console.log('点击了查询，条件:', condition);

      // 发起 AJAX 请求
      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/generalQueryByTableNameWithOriginal",
        method: "post",
        data: {
          Data: "news", // 表名
          Condition: condition, // 查询条件
        },
        success: (res) => {
          console.log('新闻表单数据', res);
          tableData.value = res; // 更新表格数据
        },
        error: (err) => {
          console.error('查询失败', err);
        },
      });
    };


    // 新闻分类切换点击事件
    const handleClick = (node) => {
      console.log('点击了', node.News_Category_SerialNumber);
      let treexw = node.News_Category_SerialNumber
      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/generalQueryByTableNameWithOriginal",
        method: "post",
        data: {
          Data: "news", //表名
          Condition: "News_Category_SerialNumber='" + treexw + "'"

        },
        success: (res) => {
          console.log('新闻表单数据', res);
          tableData.value = res
          console.log('新闻表单数据tableData', tableData);
        },
        error: (err) => {
          console.log(err)
        },
      });


    }




    // tabs点击切换事件
    const handleTabClick = (tab) => {
      console.log('当前选中tab:', tab.props.name);

      // 根据不同 tab 名称设置不同的 Row_Status 值
      let status = '';
      switch (tab.props.name) {
        case 'first':   // 全部
          status = '';  // 不传条件获取全部数据
          break;
        case 'second':  // 审核中
          status = '1'; // 对应 Row_Status='1'
          break;
        case 'third':   // 已发布
          status = '2'; // 对应 Row_Status='2'
          break;
        case 'fourth':  // 未通过
          status = '3'; // 对应 Row_Status='3'
          break;
      }

      // 调用查询方法并传递状态参数
      quernews(status);
    };



    let data = ref([])
    const defaultProps = {
      children: 'children',
      label: 'News_Category',
    }
    const categoryForm = reactive({
      Add: {
        news_category: [
          {
            // News_Category_SerialNumber:'N000001',
            News_Category: '基层风采',
            // Parent_SerialNumber:'01',
            Row_Status: '0',
            Children: {
              news: [{
                // News_SerialNumber:'NS0000000000005',
                News_Title: '风采1',
                // News_Category_SerialNumber:'N000001',
                News_Content: '内容',
                News_Views_Count: '11',
                News_Image_URL: 'dij.png',
                News_Publish_Datetime: '04-24',
                Creater_SerialNumber: '007',
                Row_Status: '0',
              }]
            }
          }
        ]
      }
    })
    onMounted(() => {
      // postNewsAdd()
      queryTree()
      quernews()

    })


    const handleDelete = (row) => {
      console.log('删除行数据:', row);
      console.log(row.News_SerialNumber);
      let mh = 'https://service.essp.top/apiForMoHe'
      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: 'news',
          Condition: "News_SerialNumber='" + row.News_SerialNumber + "'"
        },
        success: (res) => {
          console.log('修改成功', res);
          if (res.length > 0) {
            // 第二步：直接修改行状态
            res[0].Row_Status = "88"; // 直接设置为删除状态
            // 第三步：构造符合接口规范的请求体
            const deleteData = {
              Modify: {
                news: [res[0]]  // 保持原始数据结构
              }
            }
            $.ajax({
              headers: {
                "content-type": "application/x-www-form-urlencoded",
              },
              url: `${mh}/generalBusiness/generalSave`,
              method: "post",
              data: {
                Data: JSON.stringify(deleteData),
              },
              success: (res) => {
                ElMessage.success({ message: '删除成功', duration: 1400 })
                console.log('删除成功', res);


                setTimeout(() => {
                  // window.location.href = './news_page.html'
                }, 1600)
              },
              error: (err) => {
                ElMessage.error({ message: '提交失败！', duration: 1500 })
                console.log('提交失败', err)
              },
            });
          }



        },
        error: (err) => {
          ElMessage.error({ message: '提交失败！', duration: 1500 })
          console.log('提交失败', err)
        },
      });





    }
    const addnews = () => {
      console.log('添加新闻');
      // 浏览器跳转
      window.location.href = 'news_add.html?action=Add';
    }
    const handleEdit = (row) => {
      console.log('编辑行数据:', row.News_SerialNumber);
      // 编辑逻辑
      window.location.href = 'news_add.html?action=Modify&ObtainNews_SerialNumber=' + row.News_SerialNumber;
    };
    //查询新闻类别树
    const queryTree = () => {
      $.ajax({
        headers: {
          "content-type": "application/json",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/getNewsCategoryTree",
        method: "get",
        data: {
          News_Categeroy_SerialNumber: "NC0000000000012",
        },
        success: (res) => {
          console.log('查询结果', res);
          data.value = res
        },
        error: (err) => {
          console.log(err)
        },
      });
    }


    const quernews = (status = '') => {
      //查询表名获取类别编号


      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/generalQueryByTableNameWithOriginal",
        method: "post",
        data: {
          Data: "news", //表名
          Condition: status ? `Row_Status='${status}'` : "", // 添加状态过滤条件
        },
        success: (res) => {
          console.log('新闻表单数据', res);
          tableData.value = res
          console.log('新闻表单数据tableData', tableData);
        },
        error: (err) => {
          console.log(err)
        },
      });

    }
    const postNewsAdd = () => {
      // console.log(JSON.stringify(logsForm))
      $.ajax({
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        url: "https://service.essp.top/apiForMoHe/generalBusiness/generalSave",
        method: "post",
        data: {
          Data: JSON.stringify(categoryForm), //表名
          //   Condition: '',
        },
        success: (res) => {
          console.log('uuclk', res);
        },
        error: (err) => {
          console.log(err);
        },
      });
    }

    return {
      tableData,
      activeName,
      data,
      defaultProps,
      totalMembers,
      value,
      input,
      dialogVisible,
      News_Category,
      diaModify,
      shu,
      handleDel,
      handleModify,
      queren,
      check,
      handleEdit, // 确保 handleEdit 被返回
      addnews,
      handleDelete,
      handleTabClick,  // 确保 handleTabClick 被返回
      handleClick,
      handleAdd,
      disabledModify,
      Cancel,
      Cancels,
      News_modfiy
    }
  }
});

//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus);
app.mount("#app");
